package com.dixunzh.dianlailai.core.Services;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dixunzh.dianlailai.core.Utils.CDATAXmlUrils;
import com.dixunzh.dianlailai.core.Utils.SHA1;

import net.sf.json.JSONObject;

@Service
public class WxMpService {
	
	@Autowired
	private CDATAXmlUrils cDATAXmlUrils;
	
	@Autowired
	private SHA1 sha1;
	
	public Boolean msgChk(String signature,String timestamp,String nonce) {
		String TOKEN ="dexonzhwechat";
		String [] arrStr = {TOKEN,timestamp,nonce};
		Arrays.sort(arrStr);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < arrStr.length; i++) {
			sb.append(arrStr[i]);
		}
		System.out.println("signature:"+signature);
		System.out.println("singhou:"+sb.toString());
		return signature.equals(sha1.getSha1(sb.toString()));
	}
	
	public Map<String,String> resMsg(String testEntity) {
		Map<String,String> data =new HashMap<String,String>();
		String encrypt = data.get("Encrypt");
		System.out.println("Encrypt:"+encrypt);
		try {
			data=cDATAXmlUrils.xmlToMap(testEntity);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return data;
	}
	
	public String sendMsg(Map<String,String> data) {
		System.out.println(JSONObject.fromObject(data).toString());
		String resXml =null;
		try {
			Map<String,String> res = new HashMap<String,String>();
			if(data.get("Content").equals("你好")) {
				res.put("ToUserName", data.get("FromUserName"));
				res.put("FromUserName", data.get("ToUserName"));
				res.put("CreateTime",String.valueOf(new Date().getTime()));
				res.put("MsgType", "text");
				res.put("Content", "你好，欢迎光临");
				resXml = cDATAXmlUrils.mapToXml(res,true);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return resXml;
	}
}
